package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 移动端用户管理
 */
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 用户短信验证
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //调用工具类生成验证码
        String code= RandomStringUtils.random(4, false, true);
        //将验证码存到session域中
        session.setAttribute(phone,code);
        //输出打印
        log.info("验证码已发送 = {}" , code);
        //调用工具发送短信
        //SMSUtils.sendMessage(phone, code);
        //响应短信验证码已发送
        return R.success("短信验证码已发送");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto, HttpSession session){
        //获取用户的手机号和验证码
        String phone = userDto.getPhone();
        String code = userDto.getCode();
        //获取session域中的code验证码
        String cd = (String) session.getAttribute(phone);
        //判断验证码是否正确
        if (!StringUtils.equals(cd,code)){
            //验证码错误
            return R.error("验证码错误");
        }
        //判断用户是否存在
        User user = userService.lambdaQuery().eq(StringUtils.isNotBlank(phone), User::getPhone, phone).one();
        //如果用户不存在
        if (user==null){
            //注册创建用户
            user = new User();
            //设置手机号
            user.setPhone(phone);
            //设置状态
            user.setStatus(1);
            //添加用户
            userService.save(user);
        }
        //登录成功
        //往session域中存用户id
        session.setAttribute("user",user.getId());
        //响应一个用户对象
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        //销毁session
        session.invalidate();
       return R.success("退出成功");
    }
}
